<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>学生</title>
  <link rel="stylesheet" href="./bootstrap/bootstrap.min.css" />
  <link rel="stylesheet" href="./bootstrap/bootstrap-icons.css" />
  <link rel="stylesheet" href="./css/common.css" />
  <style>
    .text {
      font-size: 12px;
      margin: 0;
      padding: 5px 20px;
      color: #999;
    }

    .card i:hover {
      cursor: pointer;
    }

    .bt-1 {
      margin-top: 4px;
    }

    .card-fluid {
      border: none;
      padding: 15px;
    }

    .card .table th {
      border-color: transparent;
    }

    .form-group {
      display: flex;
      align-items: center;
      height: calc(1.5em + 1.5rem + 2px);
    }

    .form-group>label {
      width: 100px;
      text-align: right;
      padding-right: 10px;
      margin-bottom: 0;
    }

    .form-group>input {
      flex: 1;
    }

    .form-group .input {
      flex: 1;
      padding-left: 10px;
      display: flex;
    }

    .form-group .form-check {
      margin-bottom: 0;
      margin-right: 30px;
    }

    .form-group .input select {
      width: 140px;
      margin-right: 20px;
    }

    .custom-select {
      background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23999999' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e");
      background-size: 12px 12px;
    }
  </style>
</head>

<body class="application application-offset">
  <div class="container-fluid container-application">
    <div class="sidenav show" id="sidenav-main">
      <!-- Sidenav header -->
      <div class="sidenav-header d-flex align-items-center">
        <a class="navbar-brand" href="./index.html">
          <span class="logo">·ITCAST·</span>
        </a>
      </div>
      <!-- User mini profile -->
      <div class="sidenav-user d-flex flex-column align-items-center justify-content-between text-center">
        <!-- Avatar -->
        <div>
          <a href="#" class="avatar rounded-circle avatar-xl">
            <img alt="Image placeholder" src="https://yanxuan-item.nosdn.127.net/8b27deb1670c53e67c42ca3e1ed6fd12.jpg"
              class="" />
          </a>
          <div class="mt-5">
            <h5 class="mb-0 text-white">黑马前端</h5>
            <span class="d-block text-sm text-white opacity-8 mb-3">数据可视化</span>
            <a href="javascript:;" class="btn btn-sm btn-white btn-icon rounded-pill shadow hover-translate-y-n3">
              <span class="btn-inner--text">学前端来黑马</span>
            </a>
          </div>
        </div>
      </div>
      <!-- Application nav -->
      <div class="nav-application clearfix">
        <a href="./index.html" class="btn btn-square text-sm">
          <span class="btn-inner--icon d-block"><i class="bi bi-house bi-2x"></i></span>
          <span class="btn-inner--icon d-block pt-2">首页</span>
        </a>
        <a href="./student.html" class="btn btn-square text-sm active">
          <span class="btn-inner--icon d-block"><i class="bi bi-people bi-2x"></i></span>
          <span class="btn-inner--icon d-block pt-2">学生</span>
        </a>
        <a href="javascript:;" class="btn btn-square text-sm">
          <span class="btn-inner--icon d-block"><i class="bi bi-columns bi-2x"></i></span>
          <span class="btn-inner--icon d-block pt-2">排版</span>
        </a>
        <a href="javascript:;" class="btn btn-square text-sm">
          <span class="btn-inner--icon d-block"><i class="bi bi-files bi-2x"></i></span>
          <span class="btn-inner--icon d-block pt-2">资料</span>
        </a>
        <a href="javascript:;" class="btn btn-square text-sm">
          <span class="btn-inner--icon d-block"><i class="bi bi-receipt bi-2x"></i></span>
          <span class="btn-inner--icon d-block pt-2">就业</span>
        </a>
        <a href="javascript:;" class="btn btn-square text-sm">
          <span class="btn-inner--icon d-block"><i class="bi bi-gear bi-2x"></i></span>
          <span class="btn-inner--icon d-block pt-2">设置</span>
        </a>
      </div>
      <!-- Misc area -->
      <div class="card bg-gradient-warning">
        <div class="card-body">
          <h5 class="text-white">哈喽, 朋友!</h5>
          <p class="text-white mb-4">为什么不现在开始学习前端，创造一些令人惊叹的东西呢？</p>
          <a href="http://itcast.cn" class="btn btn-sm btn-block btn-white rounded-pill" target="_blank">Get started</a>
        </div>
      </div>
    </div>
    <div class="main-content position-relative">
      <nav class="navbar navbar-main navbar-expand-lg navbar-dark navbar-border" id="navbar-main">
        <div class="container-fluid">
          <!-- Navbar nav -->
          <div class="collapse navbar-collapse navbar-collapse-fade" id="navbar-main-collapse">
            <ul class="navbar-nav align-items-lg-center">
              <!-- Home  -->
              <li class="nav-item">
                <a class="nav-link pl-lg-0" href="./index.html"> 首页 </a>
              </li>
              <li class="nav-item">
                <a class="nav-link pl-lg-0" href="./index.html"> 传智教育 </a>
              </li>
              <li class="nav-item">
                <a class="nav-link pl-lg-0" href="./index.html"> 黑马程序员 </a>
              </li>
              <li class="nav-item">
                <a class="nav-link pl-lg-0" href="./index.html"> 文档 </a>
              </li>
            </ul>
            <!-- Right menu -->
            <ul class="navbar-nav ml-lg-auto align-items-center d-none d-lg-flex">
              <li class="nav-item dropdown dropdown-animate">
                <a class="nav-link pr-lg-0" href=".dropdown-menu" role="button" data-toggle="dropdown"
                  aria-haspopup="true" aria-expanded="false">
                  <div class="media media-pill align-items-center">
                    <span class="avatar rounded-circle">
                      <img alt="Image placeholder"
                        src="https://yanxuan-item.nosdn.127.net/8b27deb1670c53e67c42ca3e1ed6fd12.jpg" />
                    </span>
                    <div class="ml-2 d-none d-lg-block">
                      <span class="mb-0 text-sm font-weight-bold" id="navName">Admin</span>
                    </div>
                  </div>
                </a>
              </li>
              <li class="nav-item">
                <a class="nav-link pl-lg-0" id="logout" href="javascript:;"> 退出 </a>
              </li>
            </ul>
          </div>
        </div>
      </nav>
      <div class="page-content">
        <div class="page-title mb-3">
          <div class="row justify-content-between align-items-center">
            <div class="col-md-6 mb-3 mb-md-0">
              <h5 class="h3 font-weight-400 mb-0 text-white">Students</h5>
              <span class="text-sm text-white opacity-8">一共有 <b class="total">0</b> 位学员</span>
            </div>
            <div class="col-md-6 d-flex align-items-center justify-content-between justify-content-md-end">
              <a id="openModal" href="javascript:;" class="btn btn-sm btn-white btn-icon-only rounded-circle ml-4">
                <span class="btn-inner--icon"><i class="bi bi-plus bi-2x"></i></span>
              </a>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <div class="card card-fluid">
              <div class="table-responsive" style="min-height: 1000px">
                <table class="table align-items-center">
                  <thead>
                    <tr>
                      <th>姓名</th>
                      <th>年龄</th>
                      <th>性别</th>
                      <th>组号</th>
                      <th>期望薪资</th>
                      <th>就业薪资</th>
                      <th>籍贯</th>
                      <th>操作</th>
                    </tr>
                  </thead>
                  <tbody class="list">
                    <!-- <tr>
                      <td>张杰</td>
                      <td>20</td>
                      <td>男</td>
                      <td>第2组</td>
                      <td>10000</td>
                      <td>13000</td>
                      <td>北京北京市东城区</td>
                      <td>
                        <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen"></i></a>
                        <a href="javascript:;" class="text-danger"><i class="bi bi-trash"></i></a>
                      </td>
                    </tr> -->
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
        <!-- footer -->
        <div class="footer pt-5 pb-4 footer-light" id="footer-main">
          <div class="row text-center text-sm-left align-items-sm-center">
            <div class="col-sm-6">
              <p class="text-sm mb-0">© 2022 <a href="https://itcast.cn" class="h6 text-sm" target="_blank">前端学科</a>.
                All rights reserved.</p>
            </div>
            <div class="col-sm-6 mb-md-0">
              <ul class="nav justify-content-center justify-content-md-end">
                <li class="nav-item">
                  <a class="nav-link" href="#">Support</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="#">Terms</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link pr-0" href="#">Privacy</a>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- add Modal -->
  <div class="modal fade" id="modal">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">添加学员</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form id="form" class="g-3 row" autocomplete="off" novalidate>
            <div class="col-sm-6">
              <div class="form-group">
                <label class="input-group-label">姓名：</label>
                <input type="text" name="name" class="form-control" placeholder="请输入姓名" />
              </div>
            </div>
            <div class="col-sm-6">
              <div class="form-group">
                <label class="input-group-label">性别：</label>
                <div class="input">
                  <div class="form-check d-inline-block">
                    <input value="0" checked id="cb01" class="form-check-input" type="radio" name="gender" />
                    <label for="cb01" class="form-check-label">男</label>
                  </div>
                  <div class="form-check d-inline-block">
                    <input value="1" id="cb02" class="form-check-input" type="radio" name="gender" />
                    <label for="cb02" class="form-check-label">女</label>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-sm-6">
              <div class="form-group">
                <label class="input-group-label">年龄：</label>
                <input type="text" name="age" class="form-control" placeholder="请输入年龄" />
              </div>
            </div>
            <div class="col-sm-6">
              <div class="form-group">
                <label class="input-group-label">组号：</label>
                <input type="text" name="group" class="form-control" placeholder="请输入1-8组号" />
              </div>
            </div>
            <div class="col-sm-6">
              <div class="form-group">
                <label class="input-group-label">期望薪资：</label>
                <input type="text" name="hope_salary" class="form-control" placeholder="请输入期望薪资" />
              </div>
            </div>
            <div class="col-sm-6">
              <div class="form-group">
                <label class="input-group-label">就业薪资：</label>
                <input type="text" name="salary" class="form-control" placeholder="请输入就业薪资" />
              </div>
            </div>
            <div class="col-sm-12">
              <div class="form-group">
                <label class="input-group-label">籍贯：</label>
                <div class="input pl-0">
                  <select class="form-select custom-select" name="province">
                    <option value="">--省份--</option>
                  </select>
                  <select class="form-select custom-select" name="city">
                    <option value="">--城市--</option>
                  </select>
                  <select class="form-select custom-select" name="area">
                    <option value="">--地区--</option>
                  </select>
                </div>
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
          <button type="button" class="btn btn-blue" id="submit">确认</button>
        </div>
      </div>
    </div>
  </div>
  <script src="./bootstrap/bootstrap.min.js"></script>
  <script src="./lib/axios.js"></script>
  <script src="./lib/form-serialize.js"></script>
  <script src="./js/common.js"></script>
  <!-- 公共，token判断登录状态 -->
  <script>
    //注册和登录无token也能看
    //1.先从本地取出token值
    let token = localStorage.getItem('user-token')
    //localStorage.getItem如果没有取到对应值，则返回null
    //2.判断有无无token
    if (token === null) {
      location.href = './login.html'
    }
    //3.从本地取出用户名
    let username = localStorage.getItem('user-name')
    document.querySelector('#navName').innerHTML = username
    //4.用户退出登录功能
    document.querySelector('#logout').addEventListener('click', () => {
      //退出 
      // (1)清除本地存储内容 
      // (2)返回到登录页(不一定，根据需求来定)
      localStorage.clear()
      location.href = './login.html'
    })
  </script>
  <!-- 渲染-学生列表 -->
  <script>
    //1.标签+样式(准备好+读找)
    //2.获取数据并铺设
    //封装一个获取学生列表数据方法
    const getStudenListFn = () => {
      //axios发送请求
      axios({
        method: 'get',
        url: '/students',
      }).then(res => {
        console.log(res)
        //请求成功后调用铺设页面函数
        setStudentListFn(res.data.data)
      })
    }
    //调用函数
    getStudenListFn()

    //封装一个铺设页面的函数
    const setStudentListFn = (studentList) => {
      // console.log(studentList);
      document.querySelector('.list').innerHTML = studentList.map(item => {
        return `
        <tr>
          <td>${item.name}</td>
          <td>${item.age}</td>
          <td>${item.gender === 1 ? '女' : '男'}</td>
          <td>第${item.group}组</td>
          <td>${item.hope_salary}</td>
          <td>${item.salary}</td>
          <td>${item.province}${item.city}${item.area}</td>
          <td>
            <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen" data-id="${item.id}"></i></a>
            <a href="javascript:;" class="text-danger"><i class="bi bi-trash" data-id="${item.id}"></i></a>
          </td>
        </tr>
        `
      }).join('')
    }
  </script>
  <!-- 删除学生 -->
  <script>
    //1.给删除标签-(事件委托)tbody绑定事件
    document.querySelector('.list').addEventListener('click', function (e) {
      // console.dir(e.target);
      //判断点击的是否为删除标签(才能有删除功能)
      //字符串.indexOf('目标字符串')，返回目标字符串出现的第一次下标(不存在-1)
      if (e.target.className.indexOf('bi-trash') >= 0) {
        console.log(2);
        //3.调用删除接口
        //4.先绑定id,获取后请求
        //经验：可以给标签内容/自定义属性绑定关联的id数据
        axios({
          method: 'delete',
          url: `/students/${e.target.dataset.id}`,
        }).then(res => {
          console.log(res)
          //请求成功后重新调用学生列表函数
          getStudenListFn()
        })
      }
    })
  </script>
  <!-- 新增学生 -->
  <script>
    var myModal = new bootstrap.Modal(document.getElementById('modal'), {
      keyboard: false // 按下esc是否关闭
    })

    //初始化一个editID值为空
    let editId = null

    // 标签+样式(提示框用bootstrap准备好)
    // 没有数据铺设
    // 点击+符号，让提示框出现
    document.querySelector('.bi-plus').addEventListener('click', () => {
      myModal.show() // 显示
      //修改提示框标题
      document.querySelector('.modal-title').innerHTML = '添加学员'
      //清空表单
      document.querySelector('form').reset()
    })
    //页面显示后初始化省份列表
    let provinceSelect = document.querySelector('[name=province]')
    let citySelect = document.querySelector('[name=city]')
    let areaSelect = document.querySelector('[name=area]')
    //获取省份函数
    const initPCAFn = () => {
      axios({
        method: 'get',
        url: '/api/province',
      }).then(res => {
        console.log(res)
        //铺设省份option
        let pOptionStr = res.data.data.map(item => {
          return `<option value="${item}">--${item}--</option>`
        }).join('')
        provinceSelect.innerHTML = `<option value="">--省份--</option>` + pOptionStr
      })
    }
    // 调用函数
    initPCAFn()

    //检测省份select改变的change事件,当值变化则会获取对应的省份名，再根据对应省份获取城市
    provinceSelect.addEventListener('change', () => {
      console.log(provinceSelect.value)
      //判断是否能拿到变化的值，如果能则发送ajax请求
      if (provinceSelect.value) {
        //根据省份发送请求获取该省城市名
        axios({
          method: 'get',
          url: '/api/city',
          params: { pname: provinceSelect.value },
        }).then(res => {
          console.log(res)
          //铺设城市option
          let cOptionStr = res.data.data.map(item => {
            return `<option value="${item}">--${item}--</option>`
          }).join('')
          citySelect.innerHTML = `<option value="">--城市--</option>` + cOptionStr
        })
      } else {
        citySelect.innerHTML = `<option value="">--城市--</option>`
        areaSelect.innerHTML = `<option value="">--地区--</option>`
      }
    })
    // 检测城市select改变的change事件,当值变化则会获取对应的地区名，再根据对应城市获取地区
    citySelect.addEventListener('change', () => {
      console.log(citySelect.value)
      //如果城市值发生变化则ajax发生请求
      if (citySelect.value) {
        //根据城市发送请求获取该城市地区名
        axios({
          method: 'get',
          url: '/api/area',
          params: { pname: provinceSelect.value, cname: citySelect.value },
        }).then(res => {
          console.log(res)
          //铺设城市option
          let aOptionStr = res.data.data.map(item => {
            return `<option value="${item}">--${item}--</option>`
          }).join('')
          areaSelect.innerHTML = `<option value="">--地区--</option>` + aOptionStr
        })
      } else {
        areaSelect.innerHTML = `<option value="">--地区--</option>`
      }
    })


    //当点击确认后获取表单所有数据
    document.querySelector('#submit').addEventListener('click', async () => {
      //获取表单文本框的值(通过form-serialize.js插件)
      let formObj = serialize(document.querySelector('form'), { hash: true })
      // console.log(formObj)
      //获取表单内容后axios发送请求
      formObj.age = +formObj.age
      formObj.gender = +formObj.gender
      formObj.hope_salary = +formObj.hope_salary
      formObj.salary = +formObj.salary
      formObj.group = +formObj.group

      //通过editId值有无判断点击的是编辑还是新增页面的确认
      if (editId === null) {//新增
        await axios({
          method: 'post',
          url: '/students',
          data: formObj
        }).then(res => {
          console.log(res)
          //并且关闭提示框
          myModal.hide()
          //请求成功后在调用一次获取列表函数
          getStudenListFn()

        })
      } else {
        await axios({
          method: 'put',
          url: `/students/${editId}`,
          data: formObj
        }).then(res => {
          console.log(res)
          //并且关闭提示框
          myModal.hide()
          //请求成功后在调用一次获取列表函数
          getStudenListFn()

        })
      }
    })

  </script>
  <!-- 编辑学生 -->
  <script>
    // 点击小铅笔，让提示框出现，和添加功能使用同一个提示框(事件委托)
    document.querySelector('.list').addEventListener('click', async e => {
      if (e.target.className.indexOf('bi-pen') >= 0) {
        editId = e.target.dataset.id//保存正在编辑的id
        // console.log(1);
        //满足条件让提示框出现
        myModal.show()
        //修改提示框的标题
        document.querySelector('.modal-title').innerHTML = '编辑学生'
        //清空表单
        document.querySelector('form').reset()
        // 发送请求获取学生详细信息
        const { data: { data: student } } = await axios({
          url: `/students/${e.target.dataset.id}`
        })

        // 因为城市和地区的option数据没有，所以没办法默认回显
        //当数据回来后请求省下的城市数据
        await axios({
          method: 'get',
          url: '/api/city',
          params: { pname: student.province },
        }).then(res => {
          console.log(res)
          //铺设城市option
          let cOptionStr = res.data.data.map(item => {
            return `<option value="${item}">--${item}--</option>`
          }).join('')
          citySelect.innerHTML = `<option value="">--城市--</option>` + cOptionStr
        })
        //接着请求城市下的地区数据
        await axios({
          method: 'get',
          url: '/api/area',
          params: { pname: student.province, cname: student.city },
        }).then(res => {
          console.log(res)
          //铺设城市option
          let aOptionStr = res.data.data.map(item => {
            return `<option value="${item}">--${item}--</option>`
          }).join('')
          areaSelect.innerHTML = `<option value="">--地区--</option>` + aOptionStr
        })

        //请求成功后将返回数据铺设到对应的文本框内
        //方式一：可以一个一个标签获取，把对应值赋予上去
        // document.querySelector('form [name=name]').value = student.name
        // document.querySelector(`form [id=cb0${student.gender + 1}]`).checked = true
        // document.querySelector('form [name=province]').value = student.province

        // //方式二：
        //获取表单form标签内所有带name属性的标签集合，得到一个伪数组
        const fields = document.querySelectorAll('form [name]')
        console.log(fields);
        //Array.form()把伪数组转换成真数组
        Array.from(fields).forEach(async (item) => {
          if (item.name === 'gender') {
            if (+item.value === student[item.name]) item.checked = true
          } else {
            item.value = student[item.name]
          }
        })


      }
    })
  </script>



</html>